package org.jsserv.control;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jsserv.DOMState;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class DOMEventController extends AbstractController
{
    protected static Logger log = Logger.getLogger(DOMEventController.class);
    
    /**
     * Sends the current DOM state of the given {@link DOMState} to the client.
     * @param state
     * @param response
     */
    public static void sendDOM(DOMState state, HttpServletResponse response)
    {
        String output=state.dumpDOM();
        PrintWriter pw=null;
        try
        {
            pw=response.getWriter();
            pw.write(output);
        }
        catch(Exception e)
        {
            log.info("",e);
        }
        finally
        {
            if (pw != null)
            {
                pw.flush();            
                pw.close();
            }
        }
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        
        String id=ServletRequestUtils.getRequiredStringParameter(request, "uuid");
        
        if (log.isDebugEnabled())
        {
            log.debug("Empfange click event fuer id "+id);
        }
                
        DOMState session=(DOMState)getApplicationContext().getBean("jsSession");
        boolean canceled=session.signalEvent(id, "click");
        
        
        if (!canceled)
        {
            String url=request.getParameter("orig");
            if (log.isDebugEnabled())
                log.debug("redirect to :"+url);
            if (url != null)
            {                
                response.sendRedirect(url);
                return null;
            }
        }
        sendDOM(session, response);        
        return null;
    }
}
